import { defineComponent, watch, ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';

// 定义cdata数据结构接口（替代any，增强类型校验）
interface EnergyData {
    hours: string[];
    solarPower: number[];
    windPower: number[];
    gridPower: number[];
    batteryPower: number[];
}

// 声明组件props类型
const PropsType = {
    cdata: {
        type: Object as () => EnergyData,
        required: true
    }
} as const;

export default defineComponent({
    props: PropsType,
    setup(props) {
        // DOM引用和图表实例
        const chartRef = ref<HTMLDivElement | null>(null);
        let chartInstance: echarts.ECharts | null = null;

        // 保存已处理的时间点和对应的图表选项（避免重复处理）
        const existingHours = ref<string[]>([]);
        // 定义专用类型
        type TimelineStepOption = {
            series: Array<{
                name: string;
                type: 'bar';
                data: number[];
            }>;
        };

// 修改existingOptions类型
        const existingOptions = ref<TimelineStepOption[]>([]);
        // const existingOptions = ref<echarts.EChartsOption[]>([]);

        // 初始化图表（仅执行一次）
        const initChart = () => {
            if (chartInstance || !chartRef.value) return;

            // 创建图表实例
            chartInstance = echarts.init(chartRef.value);

            // 基础配置（固定不变的部分）
            const baseOption: echarts.EChartsOption = {
                timeline: {
                    axisType: 'category' as const, // 明确类型为category
                    autoPlay: false,
                    playInterval: 1000,
                    data: [] as { value: string }[], // 明确时间轴数据类型
                    label: {
                        formatter: (s: string) => `${s.split(':')[0]}时`
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'shadow' },
                    formatter: (params: any[]) => {
                        let result = `${params[0].name}<br/>`;
                        params.forEach(item => {
                            result += `${item.marker} ${item.seriesName}: ${item.value} kWh<br/>`;
                        });
                        return result;
                    }
                },
                legend: {
                    data: ['太阳能', '风能', '国网','电池'],
                    top: 20,
                    textStyle: { color: '#ccc' }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category' as const,
                    data: [],
                    axisLabel: { interval: 1, rotate: 45 }
                },
                yAxis: {
                    type: 'value' as const,
                    name: '发电量(kWh)'
                },
                series: [
                    {
                        name: '太阳能',
                        type: 'bar' as const,
                        stack: 'total',
                        itemStyle: { color: '#F9F98C' }
                    },
                    {
                        name: '风能',
                        type: 'bar' as const,
                        stack: 'total',
                        itemStyle: { color: '#66CCFF' }
                    },
                    {
                        name: '国网',
                        type: 'bar' as const,
                        stack: 'total',
                        itemStyle: { color: '#0ac7c0' }
                    },
                    {
                        name: '电池',
                        type: 'bar' as const,
                        stack: 'total',
                        itemStyle: { color: '#FECA04' }
                    }
                ]
            };

            // 初始化图表基础配置
            chartInstance.setOption({ baseOption });
        };

        // 监听WebSocket数据更新
        watch(
            () => props.cdata,
            (newData: EnergyData) => {
                const isFullUpdate = newData.hours.length === 24; // 假设满24个就是全量
                console.log('策略改变，右下角的表格数据更新',newData)
                // 确保图表已初始化
                // initChart();
                if (!chartInstance) return;

                // 当数据源完全变化时（如切换策略），重置已有数据
                if (newData.hours.length !== existingHours.value.length ||
                    !newData.hours.every((hour, index) => hour === existingHours.value[index])) {
                    existingHours.value = [];
                    existingOptions.value = [];
                }

                // 过滤新增的时间点（避免重复处理）
                const newHours = newData.hours.filter(hour => !existingHours.value.includes(hour));
                if (newHours.length === 0 && !isFullUpdate) return;

                if (isFullUpdate) {
                    // 整体更新（比如收到24条完整数据）--查看历史数据时
                    existingOptions.value = newData.hours.map((_, index) => ({
                        series: [
                            {
                                name: '太阳能',
                                type: 'bar' as const,
                                data: newData.solarPower.slice(0, index + 1)
                            },
                            {
                                name: '风能',
                                type: 'bar' as const,
                                data: newData.windPower.slice(0, index + 1)
                            },
                            {
                                name: '国网',
                                type: 'bar' as const,
                                data: newData.gridPower.slice(0, index + 1)
                            },
                            {
                                name: '电池',
                                type: 'bar' as const,
                                data: newData.batteryPower.slice(0, index + 1)
                            }
                        ]
                    }));
                    // existingHours.value = [...newData.hours];
                }
                else {
                    // 为新增时间点生成对应的数据选项--仿真进行时
                    newHours.forEach((_, index) => {
                        const currentIndex = existingHours.value.length + index;
                        existingOptions.value.push({
                            series: [
                                {
                                    name: '太阳能',
                                    type: 'bar' as const,
                                    data: newData.solarPower.slice(0, currentIndex + 1)
                                },
                                {
                                    name: '风能',
                                    type: 'bar' as const,
                                    data: newData.windPower.slice(0, currentIndex + 1)
                                },
                                {
                                    name: '国网',
                                    type: 'bar' as const,
                                    data: newData.gridPower.slice(0, currentIndex + 1)
                                },
                                {
                                    name: '电池',
                                    type: 'bar' as const,
                                    data: newData.batteryPower.slice(0, currentIndex + 1)
                                }
                            ]
                        });
                    });
                }

                // 更新已处理的时间点列表
                existingHours.value = [...newData.hours]; // 直接使用完整的新时间列表

                // 完全重新设置图表选项
                const fullOption: echarts.EChartsOption = {
                    // 时间轴配置
                    timeline: {
                        axisType: 'category',
                        autoPlay: false, // 可手动改为true默认播放
                        playInterval: 1000, // 播放间隔1秒
                        // 时间点列表（与options数组长度一一对应）
                        data: existingHours.value.map(hour => ({ value: hour })),
                        label: {
                            formatter: (s: string) => `${s.split(':')[0]}时`
                        }
                    },
                    // 基础配置（所有时间点共享的样式）
                    baseOption: {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: { type: 'shadow' },
                            formatter: (params: any[]) => {
                                let result = `${params[0].name}<br/>`;
                                params.forEach(item => {
                                    result += `${item.marker} ${item.seriesName}: ${item.value} kWh<br/>`;
                                });
                                return result;
                            }
                        },
                        legend: {
                            data: ['太阳能', '风能', '国网','电池'],
                            top: 20,
                            textStyle: { color: '#ccc' }
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '15%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            data: newData.hours, // x轴显示所有时间点
                            axisLabel: { interval: 1, rotate: 45 }
                        },
                        yAxis: {
                            type: 'value',
                            name: '发电量(kWh)'
                        }
                    },
                    // + 关键：每个时间点对应的图表数据（与timeline.data一一对应）
                    options: existingOptions.value.map(opt => ({
                        series: opt.series.map((s, i) => ({
                            ...s,
                            stack: 'total', // 继承堆叠配置
                            // 继承对应系列的颜色（与baseOption一致）
                            itemStyle: [
                                { color: '#F9F98C' },
                                { color: '#66CCFF' },
                                { color: '#0ac7c0' },
                                { color: '#FECA04' },
                            ][i]
                        }))
                    }))
                };

                chartInstance.setOption(fullOption, true); // 使用true参数完全替换旧选项

                // 跳转到最新时间点
                const latestIndex = existingHours.value.length - 1;
                if (latestIndex >= 0) {
                    chartInstance.dispatchAction({
                        type: 'timelineChange',
                        currentIndex: latestIndex
                    });
                }
            },
            { immediate: true, deep: true }
        );

        // 窗口大小适配
        const handleResize = () => chartInstance?.resize();

        // 生命周期管理
        onMounted(() => {
            initChart();
            window.addEventListener('resize', handleResize);
        });

        onUnmounted(() => {
            window.removeEventListener('resize', handleResize);
            if (chartInstance) {
                echarts.dispose(chartInstance);
                chartInstance = null;
            }
        });

        // 渲染图表容器
        return () => (
            <div>
                <div
                    ref={chartRef}
                    style={{ width: '100%', height: '450px' }}
                />
            </div>
        );
    }
});